package com.hjt.upload;

import com.hjt.model.MeterInfoDTO;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class ProtocolXmlBuilder {

    private StringBuilder common;
    private StringBuilder data;

    public static ProtocolXmlBuilder init(String buildingId, String gatewayId, String type) {
        ProtocolXmlBuilder protocolXmlBuilder = new ProtocolXmlBuilder();
        protocolXmlBuilder.setCommon(new StringBuilder());
        protocolXmlBuilder.getCommon().append(String.format("<common><building_id>%s</building_id><gateway_id>%s</gateway_id><type>%s</type></common>", buildingId, gatewayId, type));
        return protocolXmlBuilder;
    }

    public ProtocolXmlBuilder buildData(List<MeterInfoDTO> meters, String operation, Long collectionTime) {
        String time = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date(collectionTime));
        this.setData(new StringBuilder());
        this.data.append(String.format("<data operation=\"%s\"><sequence>01</sequence><parser>yes</parser><time>%s</time>", operation, time));
        for (MeterInfoDTO d : meters) {
            String result = d.getAddress();
            String meter = "<meter id=\"1\" name=\"" + result + "\" conn=\"conn\">" + "<function id=\"1\" name=\"" + result + "-1090\" coding=\"01A1A\" error=\"192\" sample_time=\"" + time + "\">" + d.getValue() + "</function>" + "</meter>";
            this.data.append(meter);
        }
        this.data.append("</data>");
        return this;
    }

    public String toXml() {
        return "<?xml version=\"1.0\" encoding=\"utf-8\" ?><root>" + common + data + "</root>";
    }

    public StringBuilder getCommon() {
        return common;
    }

    public void setCommon(StringBuilder common) {
        this.common = common;
    }

    public StringBuilder getData() {
        return data;
    }

    public void setData(StringBuilder data) {
        this.data = data;
    }
}
